{% extends "cashflow/base.html" %}
{% load humanize %}

{% block addition_header %}
<script type="text/javascript" src="/static/dataTables/js/jquery.dataTables.min.js"></script>
<script src="/static/amcharts/amstock.js" type="text/javascript"></script>
<link rel="stylesheet" href="/static/amcharts/style.css" type="text/css">   
{% endblock %}



{% block content %}

<section id="transactionhistory">
	<div class="page-header">
		<h1>Transaction History</h1>
  	</div>

	<a href="#change-date-filter" role="button" class="btn" data-toggle="modal">change filter</a>
	<div class="modal hide fade" id="change-date-filter" tabindex="-1" role="dialog" aria-labelledby="change-date-filter-label" aria-hidden="true">
		<form method="post" id="datepick-form">
	  	<div class="modal-header">
	    	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	    	<h3 id="change-date-filter-label">Select Filter</h3>
	  	</div>
	  	<div class="modal-body">
		    {% csrf_token %}
		    <fieldset>
		      {{ history_form.as_p }}
		    </fieldset>
	  	</div>
	  	<div class="modal-footer">
	    	<button class="btn"  type="button" data-dismiss="modal" aria-hidden="true">Close</button>
	    	<button class="btn btn-primary" id="add-transaction">Save changes</button>
	  	</div>
	  	</form>
	</div>		
	{% if date_from %}
	  from {{date_from}}
	{% endif %}
	{% if date_to %}
	  to {{date_to}}
	{% endif %}  
	
	<h3>
		{% if accountName %}Account : {{accountName}} {% endif %}
		{% if categoryName %}Category : {{categoryName}} {% endif %}
	</h3>
	
	<a href="/cashflow/category/add/"  role="button" class="btn">Add Category</a>

	<a href="#transactionAddModal" role="button" class="btn" data-toggle="modal">Add Transaction</a>
	<div class="modal hide" id="transactionAddModal" tabindex="-1" role="dialog" aria-labelledby="AddTransactionLabel" aria-hidden="true">
		<form method="post" id="transaction-form" action="/cashflow/transaction/add/">
	  	<div class="modal-header">
	    	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	    	<h3 id="AddTransactionLabel">Add Transaction</h3>
	  	</div>
	  	<div class="modal-body">
	   		{% csrf_token %}
	   	 	<fieldset>
	      		{{ transaction_form.as_p }}
	    	</fieldset>
	  	</div>
	  	<div class="modal-footer">
	    	<button class="btn"  type="button" data-dismiss="modal" aria-hidden="true">Close</button>
	    	<button class="btn btn-primary" id="add-transaction">Save changes</button>
	  	</div>
	  	</form>
	</div>	
	

	

	<script>
		$(function() {
		    $( "#id_date" ).datepicker()
				.on('changeDate', function(ev){
					$('#id_date').datepicker('hide');
				});			    

		    $( "#id_date_from" ).datepicker()				
		    	.on('changeDate', function(ev){
					$('#id_date_from').datepicker('hide');
				});
		    $( "#id_date_to" ).datepicker()
				.on('changeDate', function(ev){
					$('#id_date_to').datepicker('hide');
				});		    
   
		});
	</script>
  
  	
</section>





  




<div id="datachart" style="width: 100%; height: 200px;"></div>
<div id="incomepie" style="width: 50%; height: 250px;float: left;"></div>
<div id="expensepie" style="width: 50%; height: 250px;float: right;"></div>

<table class="table table-striped table-bordered"  id="datatable" >
  <thead>
    <tr>
      <th>Date</th>
      <th>Account</th>  
      <th>Category</th>
      <th>Description</th>
      <th>Income</th>
      <th>Expense</th>
      <th>Balance</th>      
    </tr>
	</thead>
	<tbody>

  </tbody>
	<tfoot>
		<tr>
      <th>Date</th>
      <th>Account</th>  
      <th>Category</th>
      <th>Description</th>
      <th>Income</th>
      <th>Expense</th>
      <th>Balance</th> 
		</tr>
	</tfoot>  
</table>
<script type="text/javascript" charset="utf-8">
  var rawData = [
                {% for item in history %}{
                  datetime: new Date({{ item.datetime|date:"Y" }},{{ item.datetime|date:"m" }}-1,{{ item.datetime|date:"d" }}),
                  date: "{{ item.datetime|date:"Y-m-d" }}",
                  account: "{{item.account}}",
                  category: "{{item.category}}",
                  description: "{{item.description}}",
                  income: {% if item.income %}{{item.income}}{% else %}null{% endif %},
                  expense: {% if item.expense %}{{item.expense}}{% else %}null{% endif %},
                  balance: {{item.balance}}
                  }{% if not forloop.last %},{% endif %}
                {% endfor %}
                ];
	
	
	/* Table initialisation */
	$(document).ready(function() {	
	    $('#datatable').dataTable( {
			"sPaginationType": "bootstrap",
			"oLanguage": {
				"sLengthMenu": "_MENU_ records per page"
			},
		  	"bProcessing": true,
		  	"aaData": rawData,
		  	"aoColumns": [
			    { "sTitle": "Date",  "mDataProp": "date" ,"sWidth": "80px"},
			    { "sTitle": "Account",  "mDataProp": "account" },
			    { "sTitle": "Category",  "mDataProp": "category" },
			    { "sTitle": "Description",  "mDataProp": "description" },
			    { "sTitle": "Income",  "mDataProp": "income" },
			    { "sTitle": "Expense",  "mDataProp": "expense" },
			    { "sTitle": "Balance",  "mDataProp": "balance" }
		  	]
	    } );	
	    		
	} );
	


  
  
  

  // Parse data
  function groupDataByDate(rawData) {
      var chartData = [];
      var pdate;
      var pdatetime;
      var sum_income = 0;
      var sum_expense = 0;
      var last_balance = 0;
      for (var row in rawData ) {
          if (!pdate){
            pdate = rawData[row].date;
            pdatetime = rawData[row].datetime;
          }
          if (pdate != rawData[row].date){
          
            chartData.push({
                datetime: pdatetime,
                income: sum_income,
                expense: sum_expense,
                balance: last_balance
            });  
          
            pdate = rawData[row].date;
            pdatetime = rawData[row].datetime;
            sum_income = 0;
            sum_expense = 0;
            last_balance = 0;
            }
           
          sum_income += rawData[row].income;
          sum_expense += rawData[row].expense;
          last_balance = rawData[row].balance;
      }
      chartData.push({
          datetime: pdatetime,
          income: sum_income,
          expense: sum_expense,
          balance: last_balance
      });          
      return chartData;
  }    
    
  function groupDataIncomeByCategory(rawData) {
      var chartData = [];
      var listCategory = {};
      for (var row in rawData ) {
        if (rawData[row].income){
          if (!(rawData[row].category in listCategory)){
            listCategory[rawData[row].category] = rawData[row].income;
          } else {
            listCategory[rawData[row].category] += rawData[row].income;
          }
        }
      }       
      for (var row in listCategory ) {
        chartData.push({
            category: row,
            summary: listCategory[row]
        });   
      } 
      return chartData;
  }   

  function groupDataExpenseByCategory(rawData) {
      var chartData = [];
      var listCategory = {};
      for (var row in rawData ) {
        if (rawData[row].expense){
          if (!(rawData[row].category in listCategory)){
            listCategory[rawData[row].category] = rawData[row].expense;
          } else {
            listCategory[rawData[row].category] += rawData[row].expense;
          }
        }
      }       
      for (var row in listCategory ) {
        chartData.push({
            category: row,
            summary: listCategory[row]
        });   
      } 
      return chartData;
  }      
    
    
  // Summary Chart
  AmCharts.ready(function () {
    var chart;
    var chartData = groupDataByDate(rawData);
    
    
    // SERIAL CHART
    chart = new AmCharts.AmSerialChart();
    chart.panEventsEnabled = true;
    chart.dataProvider = chartData;
    chart.categoryField = "datetime";
    chart.plotAreaBorderColor = "#DADADA";
    chart.plotAreaBorderAlpha = 1;
    chart.startDuration = 1;
    chart.columnSpacing = 0;

    // AXES
    // Category
    var categoryAxis = chart.categoryAxis;
    categoryAxis.parseDates = true; // as our data is date-based, we set this to true
    categoryAxis.minPeriod = "DD"; // our data is daily, so we set minPeriod to "DD"
    categoryAxis.dashLength = 2;
    categoryAxis.gridAlpha = 0.15;
    categoryAxis.axisColor = "#DADADA";      

    // Value
    var valueAxisBalance = new AmCharts.ValueAxis();
    valueAxisBalance.axisColor = "#FCD202";
    valueAxisBalance.axisThickness = 2;
    valueAxisBalance.gridAlpha = 0;
    valueAxisBalance.title = "Balance";
    chart.addValueAxis(valueAxisBalance);
    
    var valueAxisFlow = new AmCharts.ValueAxis();
    valueAxisFlow.position = "right";
    valueAxisFlow.axisColor = "#B0DE09";
    valueAxisFlow.axisThickness = 2;
    valueAxisFlow.gridAlpha = 0;
    valueAxisFlow.title = "Summary";
    chart.addValueAxis(valueAxisFlow);      

    // GRAPHS
    var graphIncome = new AmCharts.AmGraph();
    graphIncome.valueAxis = valueAxisFlow;
    graphIncome.type = "column";
    graphIncome.title = "Income";
    graphIncome.valueField = "income";
    graphIncome.balloonText = "Income:[[value]]";
    graphIncome.lineAlpha = 0;
    graphIncome.fillColors = "#B0DE09";
    graphIncome.fillAlphas = 1;
    chart.addGraph(graphIncome);

    var graphExpense = new AmCharts.AmGraph();
    graphExpense.valueAxis = valueAxisFlow;
    graphExpense.type = "column";
    graphExpense.title = "Expenses";
    graphExpense.valueField = "expense";
    graphExpense.balloonText = "Expenses:[[value]]";
    graphExpense.lineAlpha = 0;
    graphExpense.fillColors = "#FF6600";
    graphExpense.fillAlphas = 1;
    chart.addGraph(graphExpense);

    var graphBalance = new AmCharts.AmGraph();
    graphBalance.valueAxis = valueAxisBalance;
    graphBalance.type = "smoothedLine";
    graphBalance.title = "Balance";
    graphBalance.valueField = "balance";
    graphBalance.balloonText = "Balance:[[value]]";
    graphBalance.lineThickness = 4;
    graphBalance.bullet = "round";
    graphBalance.bulletSize = 12;
    graphBalance.bulletBorderColor = "#FFFFFF";
    graphBalance.bulletBorderThickness = 2; 
    graphBalance.lineColor = "#FCD202";
    graphBalance.negativeLineColor = "#FF6600";
    chart.addGraph(graphBalance);
              
    // CURSOR
    var chartCursor = new AmCharts.ChartCursor();
    chartCursor.zoomable = false;
    chartCursor.cursorPosition = "mouse";
    chart.addChartCursor(chartCursor);
       
    // LEGEND
    var legend = new AmCharts.AmLegend();
    legend.position = "absolute";
    legend.top = "5px";
    legend.left = "10px";
    chart.addLegend(legend);

    // WRITE
    chart.write("datachart");
  });
    

  // Income Pie
  AmCharts.ready(function () {
      var input =  rawData;
      var chartData = groupDataIncomeByCategory(rawData); 
  
      // PIE CHART
      chart = new AmCharts.AmPieChart();
      chart.dataProvider = chartData;
      chart.titleField = "category";
      chart.valueField = "summary";
      chart.labelRadius = 30;
      chart.labelText = "[[title]]:[[percents]]%";      
      chart.addTitle("Summary Income");

      // LEGEND
      legend = new AmCharts.AmLegend();
      legend.align = "center";
      legend.markerType = "circle";
      legend.position = "right";
      chart.addLegend(legend);

      // WRITE
      chart.write("incomepie");
  });
  
  // Expense Pie
  AmCharts.ready(function () {
      var input =  rawData;
      var chartData = groupDataExpenseByCategory(rawData); 
  
      // PIE CHART
      chart = new AmCharts.AmPieChart();
      chart.dataProvider = chartData;
      chart.titleField = "category";
      chart.valueField = "summary";
      chart.labelRadius = 30;
      chart.labelText = "[[title]]:[[percents]]%";    
      chart.addTitle("Summary Expense");      

      // LEGEND
      legend = new AmCharts.AmLegend();
      legend.align = "center";
      legend.markerType = "circle";
      legend.position = "right";
      chart.addLegend(legend);

      // WRITE
      chart.write("expensepie");
  });  

</script>
{% endblock %}